package cn.liumouren.tool.security.autoconfigure.component.filter;

import cn.liumouren.tool.security.autoconfigure.SecurityProperties;
import cn.liumouren.tool.security.autoconfigure.exception.TokenFormatException;
import cn.liumouren.tool.security.core.DlFilter;
import cn.liumouren.tool.security.core.Permission;
import cn.liumouren.tool.security.core.TokenProcessor;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Daniel Liu
 * @date 2021/3/12 17:27
 */
public class CheckTokenFilter extends DlFilter {

    private final SecurityProperties properties;
    private final TokenProcessor tokenProcessor;

    public CheckTokenFilter(SecurityProperties properties, TokenProcessor tokenProcessor) {
        this.properties = properties;
        this.tokenProcessor = tokenProcessor;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//        System.out.println("经过tokenFilter...");
        String header = request.getHeader(properties.getTokenHeader());
        if (header == null || !header.startsWith(properties.getPrefix())) {
            throw new TokenFormatException("no qualified token.");
        }
        Permission permission;
        try {
            permission = tokenProcessor.parse(header.replace(properties.getPrefix(), ""));
        } catch (Exception e) {
            throw new RuntimeException("token parse err.");
        }
        request.setAttribute("permission", permission);

        filterChain.doFilter(request, response);
    }

}
